package com.xpqh.ksg.common.utils;


import com.alibaba.fastjson2.JSON;
import com.xpqh.ksg.common.enums.result.BizExceptionEnum;
import com.xpqh.ksg.exception.WebApiException;
import lombok.extern.slf4j.Slf4j;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Slf4j
public class RenderUtil {

    // CORS 相关响应头
    private static final String ALLOW_ORIGIN = "*";
    private static final String ALLOW_CREDENTIALS = "true";
    private static final String ALLOW_METHODS = "GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS";
    private static final String MAX_AGE = "86400";
    private static final String ALLOW_HEADERS = "*";
    private static final String EXPOSE_HEADERS = "Authorization";

    public static void renderJson(HttpServletResponse response, Object jsonObject) {
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");

        // 设置 CORS 响应头
        response.setHeader("Access-Control-Allow-Origin", ALLOW_ORIGIN);
        response.setHeader("Access-Control-Allow-Credentials", ALLOW_CREDENTIALS);
        response.setHeader("Access-Control-Allow-Methods", ALLOW_METHODS);
        response.setHeader("Access-Control-Max-Age", MAX_AGE);
        response.setHeader("Access-Control-Allow-Headers", ALLOW_HEADERS);
        response.setHeader("Access-Control-Expose-Headers", EXPOSE_HEADERS);

        PrintWriter writer = null;
        try {
            writer = response.getWriter();
            String jsonString = JSON.toJSONString(jsonObject);
            writer.write(jsonString);
            writer.flush();
        } catch (IOException e) {
            log.error("Failed to write JSON response", e);
            throw new WebApiException(BizExceptionEnum.WRITE_ERROR);
        } catch (Exception e) {
            log.error("Failed to serialize JSON object", e);
            throw new WebApiException(BizExceptionEnum.JSON_SERIALIZE_ERROR);
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }
}
